<script setup lang="ts">
import { request } from '@/api'
import b64toBlob from 'b64-to-blob';
import { closeToast, showLoadingToast, showSuccessToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'

//修改头像
//定义头像抽屉框是否显示
const showAvatarSheet = ref(false)
const avatarActions = [{ name: '拍照' }, { name: '相册' }]
// 选项触发 (拍照 or 相册)
const onSelectAvatar = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    // 拍照上传
    console.log('拍照上传')
    const data = await mk.pickerCamera()
    console.log('拍照上传', data)
  } else if (index === 1) {
    // 相册上传
    console.log('相册上传')
    const data = await mk.pickerPhoto()
    console.log('相册上传', data)
    onUpdataAvatar(data)
  }
}
/*
 思路分析: 
 头像上传
 1. 查看相册及拍照返回的格式 -> base64字符串
 2. 将base64字符串转成二进制流数据 (接口需要)
 3. 创建一个formData对象 
 4. 将二进制数据添加到formData对象当中
 5. 根据接口文档, 实现上传
 6. 渲染页面中的图片组件
 7. 优化
 7.1 添加loading效果
 7.2 返回上一页时, 更新头像
*/

//上传头像
const onUpdataAvatar = async(data:string)=>{
  showLoadingToast({ message: '上传中...', duration: 0, forbidClick: true})
  const image = b64toBlob(data, 'image/jpeg')
  const fd = new FormData()
  fd.append('file', image,Date.now()+'.jpeg')
  const res = await request.post<MkResponse<{avatar:string}>>('member/profile/avatar', fd)
  closeToast()
  profile.value.avatar = res.data.result.avatar
  console.log('上传头像', res.data.result.avatar)
  const user = mk.queryUser()
  user.avatar = res.data.result.avatar
  mk.updateUser(user)
}

// 选择生日日期
// 定义控制日期选择器的显示隐藏
const showBirthdayPopup = ref(false)
// 当前选中的绑定时间
const birthday = ref(['2000', '08', '04'])
// 确认选中日期
const onChangeBirthday = (data: any) => {
  console.log('选中的日期', data)
  profile.value.birthday = birthday.value.join('-')
  showBirthdayPopup.value = false
}

//所在地
const showLocationPopup = ref(false)
const areaColumns = ref<AreaColumns>()
onMounted(async () => {
  const data = await mk.getAreaColumns()
  console.log('地区数据', data)
  areaColumns.value = data
})
//选择地区
// const onSelectedLocation = ({
//   selectedValues,
//   selectedOptions,
//   selectedIndexes,
// }: any) => {
// 形参解构 => 获取形参时, 直接解构数据 (快速获取值)  
// const onSelectedLocation = ({ selectedValues }: { selectedValues: string[] }) => {

const onSelectedLocation = (data:{
  selectedValues:number[]
}) => {
  console.log(data.selectedValues)
    // 往profile用户信息中新增三个字段参数 (满足接口的需要)
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
  
  // 省
  const province = areaColumns.value?.province_list[data.selectedValues[0]]
  // 市
  const city = areaColumns.value?.city_list[data.selectedValues[1]]
  // 区
  const county = areaColumns.value?.county_list[data.selectedValues[2]]
  console.log('省市区', province, city, county);
  profile.value.fullLocation = `${province} ${city} ${county}`
   showLocationPopup.value = false
}

//职业选择
// 4. 选择职业
const professionColumns = [
  { text: '鸿蒙应用开发工程师', value: '鸿蒙应用开发工程师' },
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data:{
  selectedIndexes:number[]
}) => {
  console.log(data.selectedIndexes)
  const profession = professionColumns[data.selectedIndexes[0]]
  profile.value.profession = profession.value
  showProfessionPopup.value = false
}

//用户信息接口获取
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  closeToast()
  profile.value = res.data.result
  console.log(profile)
   // 选中生日控件时 -> 默认日期展示是当前用户接口返回的birthday值 (合理)
  birthday.value = res.data.result.birthday.split('-')
})

// 保存用户信息
const loading = ref(false)
const onSubmit=async()=>{
  // 1. 展示loading效果
  // 2. 发送请求
  // 3. 拿到用户信息
  // 4. 更新鸿蒙测的user数据
  // 5. 关闭loading效果
  loading.value = true
  const res = await request.put<MkResponse<ProfileInfo>>('/member/profile',profile.value)
  console.log('用户信息', res.data.result)
  mk.updateUser(res.data.result)
  loading.value = false
  showSuccessToast('保存成功~')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <van-action-sheet
      @select="onSelectAvatar"
      v-model:show="showAvatarSheet"
      :actions="avatarActions"
      style="padding-bottom: 20px"
      cancel-text="取消"
      close-on-click-action
    />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field
        label="昵称"
        v-model="profile.nickname"
        placeholder="请输入昵称"
      ></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        @click="showBirthdayPopup = true"
        v-model="profile.birthday"
      ></van-field>
      <van-popup
        v-model:show="showBirthdayPopup"
        position="bottom"
        :style="{ height: '30%' }"
      >
        <van-date-picker
          v-model="birthday"
          title="选择日期"
          @cancel="showBirthdayPopup = false"
          @confirm="onChangeBirthday"
          :min-date="new Date('1980-01-01')"
          :max-date="new Date()"
        />
      </van-popup>
      <van-field
        label="所在地"
        readonly
        placeholder="请选择所在地"
        @click="showLocationPopup = true"
        v-model="profile.fullLocation"
      ></van-field>
      <van-popup v-model:show="showLocationPopup" position="bottom">
        <van-area
          title="城市选择"
          :area-list="areaColumns"
          @cancel="showLocationPopup = false"
          @confirm="onSelectedLocation"
        />
      </van-popup>
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        v-model="profile.profession"
        @click="showProfessionPopup = true"
      ></van-field>
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-picker
          title="标题"
          :columns="professionColumns"
          @confirm="onChangeProfession"
          @cancel="showProfessionPopup = false"
        />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button  @click="onSubmit" loading-text="加载中..." :loading="loading" round block type="primary"> 保存资料 </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
